<template>
  <div class="snake-game">
    <h1>贪吃蛇小游戏</h1>
    <div class="game-info">
      <div>分数: {{ score }}</div>
      <div>等级: {{ level }}</div>
      <button @click="startGame" v-if="!gameStarted">开始游戏</button>
      <button @click="pauseGame" v-else-if="!isPaused">暂停</button>
      <button @click="resumeGame" v-else>继续</button>
      <button @click="resetGame">重置</button>
    </div>
    <div class="game-container" ref="gameContainer" :style="backgroundStyle">
      <div 
        class="snake-cell" 
        v-for="cell in grid" 
        :key="cell.id"
        :style="getCellStyle(cell)"
      >
        <img 
          v-if="cell.type === 'head'" 
          :src="getHeadImage()" 
          class="cell-image"
        />
        <img 
          v-else-if="cell.type === 'body'" 
          :src="currentBodyImage" 
          class="cell-image"
        />
        <img 
          v-else-if="cell.type === 'food'" 
          :src="foodImage" 
          class="cell-image food-image"
        />
      </div>
    </div>
    <div v-if="gameOver" class="game-over">
      <h2>游戏结束!</h2>
      <p>最终分数: {{ score }}</p>
      <button @click="resetGame">重新开始</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SnakeGame',
  data() {
    return {
      rows: 20,
      cols: 20,
      grid: [],
      snake: [],
      direction: 'right',
      nextDirection: 'right',
      food: null,
      gameStarted: false,
      gameOver: false,
      isPaused: false,
      score: 0,
      level: 1,
      speed: 200,
      gameInterval: null,
      // 不同方向的蛇头图片
      headImages: {
        up: require('@/assets/up.png'),
        down: require('@/assets/down.png'),
        left: require('@/assets/left.png'),
        right: require('@/assets/right.png')
      },
      // 蛇身图片
      bodyImages: [
        require('@/assets/body.png')
      ],
      // 食物图片
      foodImage: require('@/assets/food.png'),
      // 背景图片
      backgroundImage: require('@/assets/game-bg.png'),
      // 当前使用的身体图片索引
      currentBodyImageIndex: 0
    }
  },
  computed: {
    cellSize() {
      const containerSize = Math.min(
        this.$refs.gameContainer?.offsetWidth || 400, 
        400
      );
      return containerSize / this.cols;
    },
    // 当前使用的身体图片
    currentBodyImage() {
      return this.bodyImages[this.currentBodyImageIndex];
    },
    // 背景样式
    backgroundStyle() {
      return {
        backgroundImage: `url(${this.backgroundImage})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center'
      };
    }
  },
  created() {
    this.initGrid();
    window.addEventListener('keydown', this.handleKeyPress);
  },
  beforeDestroy() {
    window.removeEventListener('keydown', this.handleKeyPress);
    clearInterval(this.gameInterval);
  },
  methods: {
    initGrid() {
      // 初始化网格，为每个单元格添加唯一ID
      this.grid = Array(this.rows * this.cols).fill().map((_, i) => ({
        id: i,
        type: null,
        row: Math.floor(i / this.cols),
        col: i % this.cols
      }));
      
      const startRow = Math.floor(this.rows / 2);
      const startCol = Math.floor(this.cols / 2);
      this.snake = [
        { row: startRow, col: startCol },
        { row: startRow, col: startCol - 1 },
        { row: startRow, col: startCol - 2 }
      ];
      
      this.placeFood();
      this.updateGrid();
    },
    
    updateGrid() {
      // 重置网格类型
      this.grid.forEach(cell => {
        cell.type = null;
      });
      
      // 绘制蛇
      this.snake.forEach((segment, i) => {
        const index = segment.row * this.cols + segment.col;
        if (index >= 0 && index < this.grid.length) {
          this.grid[index].type = i === 0 ? 'head' : 'body';
        }
      });
      
      // 绘制食物
      if (this.food) {
        const index = this.food.row * this.cols + this.food.col;
        if (index >= 0 && index < this.grid.length) {
          this.grid[index].type = 'food';
        }
      }
    },
    
    getHeadImage() {
      return this.headImages[this.direction];
    },
    
    placeFood() {
      const availableCells = [];
      for (let row = 0; row < this.rows; row++) {
        for (let col = 0; col < this.cols; col++) {
          const isSnake = this.snake.some(segment => 
            segment.row === row && segment.col === col
          );
          if (!isSnake) {
            availableCells.push({ row, col });
          }
        }
      }
      
      if (availableCells.length > 0) {
        const randomIndex = Math.floor(Math.random() * availableCells.length);
        this.food = availableCells[randomIndex];
      }
    },
    
    moveSnake() {
      if (this.isPaused || !this.gameStarted || this.gameOver) return;
      
      this.direction = this.nextDirection;
      
      const head = { ...this.snake[0] };
      switch (this.direction) {
        case 'up': head.row--; break;
        case 'down': head.row++; break;
        case 'left': head.col--; break;
        case 'right': head.col++; break;
      }
      
      if (this.checkCollision(head)) {
        this.gameOver = true;
        clearInterval(this.gameInterval);
        return;
      }
      
      this.snake.unshift(head);
      
      if (head.row === this.food.row && head.col === this.food.col) {
        this.score += 10 * this.level;
        
        // 切换身体图片
        this.currentBodyImageIndex = (this.currentBodyImageIndex + 1) % this.bodyImages.length;
        
        if (this.score >= this.level * 100) {
          this.level++;
          this.speed = Math.max(50, this.speed - 20);
          clearInterval(this.gameInterval);
          this.startGameLoop();
        }
        
        this.placeFood();
      } else {
        this.snake.pop();
      }
      
      this.updateGrid();
    },
    
    checkCollision(head) {
      // 检查墙壁碰撞
      if (
        head.row < 0 ||
        head.row >= this.rows ||
        head.col < 0 ||
        head.col >= this.cols
      ) {
        return true;
      }
      
      // 检查自身碰撞（除了尾部，因为尾部会移动）
      for (let i = 0; i < this.snake.length - 1; i++) {
        if (this.snake[i].row === head.row && this.snake[i].col === head.col) {
          return true;
        }
      }
      
      return false;
    },
    
    handleKeyPress(event) {
      if (!this.gameStarted || this.isPaused) return;
      
      switch (event.key) {
        case 'ArrowUp':
          if (this.direction !== 'down') this.nextDirection = 'up';
          break;
        case 'ArrowDown':
          if (this.direction !== 'up') this.nextDirection = 'down';
          break;
        case 'ArrowLeft':
          if (this.direction !== 'right') this.nextDirection = 'left';
          break;
        case 'ArrowRight':
          if (this.direction !== 'left') this.nextDirection = 'right';
          break;
      }
    },
    
    startGame() {
      this.gameStarted = true;
      this.gameOver = false;
      this.startGameLoop();
    },
    
    startGameLoop() {
      clearInterval(this.gameInterval);
      this.gameInterval = setInterval(this.moveSnake, this.speed);
    },
    
    pauseGame() {
      this.isPaused = true;
      clearInterval(this.gameInterval);
    },
    
    resumeGame() {
      this.isPaused = false;
      this.startGameLoop();
    },
    
    resetGame() {
      clearInterval(this.gameInterval);
      this.gameStarted = false;
      this.gameOver = false;
      this.isPaused = false;
      this.score = 0;
      this.level = 1;
      this.speed = 200;
      this.direction = 'right';
      this.nextDirection = 'right';
      this.currentBodyImageIndex = 0;
      this.initGrid();
    },
    
    getCellStyle(cell) {
      return {
        position: 'absolute',
        width: `${this.cellSize}px`,
        height: `${this.cellSize}px`,
        left: `${cell.col * this.cellSize}px`,
        top: `${cell.row * this.cellSize}px`,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      };
    }
  }
}
</script>

<style scoped>
.snake-game {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-family: Arial, sans-serif;
  padding: 20px;
  max-width: 100%;
  overflow: hidden;
}

.game-info {
  margin: 20px 0;
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
}

.game-container {
  position: relative;
  width: 100%;
  max-width: 400px;
  height: 400px;
  border: 2px solid #333;
  box-sizing: border-box;
  overflow: hidden;
  background-color: #222; /* 添加深色背景使蛇更明显 */
}

.snake-cell {
  position: absolute;
  /* 移除过渡效果，使移动更精确 */
}

/* 修改蛇身单元格样式 */
.snake-cell[data-type="body"] {
  width: calc(100% + 2px); /* 略微超出网格边界 */
  height: calc(100% + 2px);
  margin-left: -1px;
  margin-top: -1px;
  z-index: 1; /* 确保蛇身在背景之上 */
}

/* 修改蛇头单元格样式 */
.snake-cell[data-type="head"] {
  width: 100%;
  height: 100%;
  z-index: 2; /* 确保蛇头在最上层 */
}

.cell-image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 改为cover以填满整个单元格 */
  image-rendering: pixelated;
}

/* 调整食物图片样式 */
.food-image {
  width: 80%;
  height: 80%;
  margin: 10%;
  object-fit: contain;
  animation: pulse 0.5s infinite alternate;
}

@keyframes pulse {
  from { transform: scale(1); }
  to { transform: scale(1.1); }
}

.game-over {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  z-index: 100;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
  min-width: 80px;
}

button:hover {
  background-color: #45a049;
}

@media (max-width: 500px) {
  .game-info {
    flex-direction: column;
    gap: 10px;
  }
  
  button {
    width: 100%;
    max-width: 200px;
  }
  
  .game-container {
    height: 300px;
  }
}
</style>